<template>
  <div class="warpper">
    <div class="toolbar">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" label-width="130px" label-position="right">
        <el-form-item label="Name">
          <el-input v-model="searchForm.name" @keyup.enter.native="search" placeholder="Enter Name"
            style="width: 212%;">
          </el-input>
        </el-form-item>
        <el-form-item label="Contract Date" style="margin-left: 250px;">
          <el-date-picker v-model="searchForm.time" type="datetimerange" range-separator="-"
            start-placeholder="Start Date" end-placeholder="End Date" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button @click="find()" plain style="margin-left: 24px;">Search</el-button>
          <el-button type="primary" v-permission="['suppliers.store']" plain @click="supperadd">+ New</el-button>
          <el-button type="primary" v-permission="['suppliers.view']" plain @click="exportData">export</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table">
      <el-table @sort-change="handleSortChange" :data="tableData" size="small" stripe border style="width: 100%">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="name" label="Supplier Name" width="220" align="center" sortable="name"  />
        <el-table-column prop="attention_name" label="Attention Name" width="140" align="center" sortable="attention_name" />
        <el-table-column prop="email" label="Email" width="160" sortable="email" />
        <el-table-column prop="tel" label="Tel" width="100" sortable="tel" />
        <el-table-column prop="address" label="Address" width="200" sortable="address" />
        <el-table-column prop="cenddate" label="Contract Date" width="200" align="center" sortable="cenddate" >
          <template v-slot="scope">
            <span v-if="scope.row.cenddate && parseDateStr(scope.row.cenddate)<mydate"
              style="color:#fb8503">Expired</span>
            <span v-else>{{ scope.row.cstartdate }}~{{ scope.row.cenddate }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="skunum_count" label="Product" align="center" sortable="skunum_count" >
          <template v-slot="scope">
            {{scope.row.skunum_count}}
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="Created Time" min-width="200" sortable="created_at" >
          <template v-slot="scope">
            <span>{{ scope.row.created_at | showDateTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="Actions" width="200">
          <template slot-scope="scope">
            <el-button plain v-permission="['suppliers.show']" @click="edit(scope.row.id)">edit</el-button>
            <el-button plain v-permission="['suppliers.destroy']" type="danger"
              @click="del(scope.row.id)">delete</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page">
      <el-pagination v-if="isPaginate" background :current-page="page.current_page" :page-sizes="page.sizes"
        :page-size="page.per_page" layout="prev, pager, next" :total="page.total" @size-change="sizeChange"
        @current-change="currentChange" />
    </div>
    <div class="form">
      <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false"
        customClass="customWidth">
        <el-form v-if="dialogFormVisible" ref="ruleForm" :model="formData" :rules="rules" label-width="160px"
          style="width:85%">

          <el-form-item label="Company Name" prop="name" style="width:460px">
            <el-input v-model="formData.name" autocomplete="off" placeholder="Name" />
          </el-form-item>


          <el-form-item label="Attention Name" prop="attention_name" style="width: 460px;">
            <el-input v-model="formData.attention_name" autocomplete="off" placeholder="attention_name" />
          </el-form-item>


          <el-form-item label="Email" prop="email" style="width: 460px;">
            <el-input v-model="formData.email" placeholder="email"></el-input>
          </el-form-item>

          <el-form-item label="Tel" prop="tel" style="width: 460px;">
            <el-input v-model="formData.tel" placeholder="Tel"></el-input>
          </el-form-item>

          <el-form-item label="Address" prop="address" style="width: 460px;">
            <el-input v-model="formData.address" placeholder="Address"></el-input>
          </el-form-item>


          <el-form-item label="Currency" prop="currency">
            <el-select v-model="formData.currency" placeholder="Choose Currency" style="width:300px">
              <el-option v-for="item in currency" :key="item.id" :label="item.name" :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="Credit Term" prop="Credit Term">
            <el-input-number v-model="formData.credit_term" :min="1"></el-input-number>
            <el-select v-model="formData.credit_term_type" placeholder="Choose Credit Term" style="width: 115px;">
              <el-option v-for="item in credit_term_type" :key="item.id" :label="item.name" :value="item.name"
                style="width: 115px;">
              </el-option>
            </el-select>
          </el-form-item>

        </el-form>


        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="save('ruleForm')">Submit</el-button>
          <el-button @click="dialogFormVisible = false">Cancel</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import CURD from "@/mixin/CURD";
  import {
    exportData as skuexport
  } from "@/api/supplier";
  export default {
    name: "supplierIndex",
    mixins: [CURD],
    data() {
      return {
        mydate: '',
        formData: {

        },
        credit_term_type: [{
          id: 1,
          name: "day",
        }, {
          id: 2,
          name: "week",
        }, {
          id: 3,
          name: "month",
        }],
        status: [{
          id: 1,
          name: "Normal",
        }, {
          id: 2,
          name: "Hidden",
        }],
        currency: [{
          id: 1,
          name: "sgd",
        }, {
          id: 2,
          name: "usd",
        }],
        module: "supplier",
        newTitle: "New supplier",
        editTitle: "Edit supplier",
        isPaginate: true,
        isUploadFile: false,
        fileReader: new FileReader(),
        isShow: false,
        searchForm: {

        },

      };
    },
    async created() {
      const today = new Date();
      //const currentDate = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
      this.mydate = today
    },
    methods: {
      handleSortChange({ prop, order }) {
        this.searchForm.orderBy = prop;
        this.searchForm.orderType = order === 'ascending' ? 'asc' : 'desc';
        this.fetchData();
      },
      async fetchData() {
        let { index } = require(`@/api/${this.module}`);
        const res = await index(
          this.page.current_page,
          this.page.per_page,
          this.searchForm  // 包含了排序参数
        );
        if (
          res.data instanceof Object &&
          typeof this.transfromData === "function"
        ) {
          let data = this.transfromData(res.data);
          this.tableData = data;
        } else {
          this.tableData = res.data;
        }
        if (res.meta) {
          // 分页
          res.meta.per_page = parseInt(res.meta.per_page);
          this.page = Object.assign(this.page, res.meta);
        } else {
          this.isPaginate = false; // 不分页
        }
      },
      async exportData() {
        const resv = await skuexport();
        this.exportFile("data", resv);
      },
      exportFile(fileName, res) {
        const content = res;
        const blob = new Blob([content], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        if ("download" in document.createElement("a")) {
          // 非IE下载
          const elink = document.createElement("a");
          elink.download = fileName;
          elink.style.display = "none";
          elink.href = window.URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          window.URL.revokeObjectURL(elink.href); // 释放 URL对象
          document.body.removeChild(elink);
        } else {
          // IE10+下载
          window.navigator.msSaveBlob(blob, fileName);
        }
      },
      parseDateStr(dateStr) {
        const [month, day, year] = dateStr.split('-').map(Number);
        return new Date(year, month - 1, day);
      },
      supperadd() {
        this.$router.push({
          path: '/supplier/supplieradd',
          query: {
            id: null
          }
        })
      },
      async edit(id) {
        this.$router.push({
          path: '/supplier/editsupplier',
          query: {
            id: id
          }
        })
      },
    }
  }
</script>
<style>
  .customWidth {
    width: 80%;
  }

  .table,
  .toolbar,
  .page {
    margin: 20px;
  }

  .toolbar {
    margin-top: 10px;
    padding: 5px;
  }

  .table {
    margin-bottom: 10px;
  }

  .page {
    margin-top: 10px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 78px;
    height: 78px;
    line-height: 78px;
    text-align: center;

  }

  .green-text {
    color: green;
  }

  .red-text {
    color: red;

  }

  .yellow-text {
    color: yellow;

  }
</style>
